<template>
	<div class="ecoflow-form">
		<!-- 顶部标题和通知 -->

		<!-- 服务类型选择 -->
		<div class="section">
			<div class="section-header">
				<van-icon name="todo-list" size="20" />
				<h2>{{ t('baseInfo.title') }}</h2>
			</div>
			<van-cell-group>
				<van-cell
					:title="`${t('orderSuccess.orderId')}${
						orderStore.order_no
					}`"
				/>
				<van-cell
					:title="`${t('baseInfo.remark')}：${
						orderStore.requirement_text
					}`"
				/>
				<van-cell
					:title="`${t('appointment.title')}：${
						orderStore.service.service_date
					} ${serviceTimeDisplay}`"
				/>
				<van-cell
					:title="`${t('baseInfo.service')}：${
						orderStore.customer.service_category_name +
						'-' +
						orderStore.customer.service_name
					}`"
				/>
				<van-cell
					v-if="
						orderStore.customer.additional_requirements &&
						orderStore.customer.additional_requirements.length > 0
					"
					:title="`${t(
						'baseInfo.extra'
					)}：${orderStore.customer.additional_requirements.join(
						','
					)}`"
				/>
				<van-cell
					:title="`${t('install.position')}：${
						orderStore.customer.install_position
					}`"
				/>
				<van-cell
					:title="`${t('install.wallType')}：${
						orderStore.customer.wall_category
					}`"
				/>
				<van-cell
					:title="`${t('baseInfo.remark')}：${
						orderStore.customer.remarks
					}`"
				/>
			</van-cell-group>
		</div>

		<!-- 客户信息 -->
		<div class="section">
			<div class="section-header">
				<van-icon name="contact" size="20" />
				<h2>{{ t('contact.title') }}</h2>
			</div>
			<van-cell-group>
				<van-cell
					:title="`${t('baseInfo.name')}：${
						orderStore.customer.name
					}`"
				/>
				<van-cell
					:title="`${t('baseInfo.phone')}：${
						orderStore.customer.mobile
					}`"
				/>
				<van-cell
					:title="`${t('baseInfo.address')}：${
						orderStore.customer.address
					}`"
				/>
			</van-cell-group>
		</div>

		<!-- 安装人员信息 -->
		<!-- <div class="section">
      <div class="section-header">
        <van-icon name="friends" size="20" />
        <h2>安装人员信息</h2>
      </div>
      <van-cell-group>
        <van-field v-model="form.installer.name" label="姓名/公司名称" placeholder="请输入姓名或公司名称" />

        <van-field v-model="form.installer.contactInfo" label="联系信息" placeholder="请输入联系信息" />
      </van-cell-group>
    </div> -->

		<!-- 产品评估 -->
		<div class="section">
			<div class="section-header">
				<van-icon name="completed" size="20" />
				<h2>{{ t('install.photo') }}</h2>
			</div>
			<div class="image-scroll-list">
				<div
					v-for="(item, idx) in allImages"
					:key="`img-${idx}`"
					class="image-item"
					@click="previewImage(idx)"
				>
					<van-image
						:src="item"
						width="100"
						height="100"
						fit="cover"
						style="border-radius: 8px; cursor: pointer"
					/>
				</div>
			</div>
		</div>

		<!-- 确认和条款 -->
		<div class="section">
			<div class="section-header">
				<van-icon name="description" size="20" />
				<h2>{{ t('baseInfo.terms') }}</h2>
			</div>
			<van-cell-group>
				<!-- <van-field label="最终发票金额是否与估价一致">
					<template #input>
						<van-radio-group
							v-model="form.invoiceMatch"
							direction="horizontal"
						>
							<van-radio :name="true">是</van-radio>
							<van-radio :name="false">否</van-radio>
						</van-radio-group>
					</template>
</van-field> -->
				<!-- <van-field
					v-if="!form.invoiceMatch"
					v-model="form.invoiceReason"
					type="textarea"
					placeholder="请说明原因"
					rows="2"
					autosize
				/> -->

				<!-- 条款内容 -->
				<van-collapse v-model="activeCollapse">
					<van-collapse-item
						:title="t('terms.detailTitle')"
						name="terms"
					>
						<div class="terms-content">
							<h3>{{ t('terms.licenseTitle') }}</h3>
							<p>{{ t('terms.licenseContent') }}</p>

							<h3>{{ t('terms.serviceTitle') }}</h3>
							<p>{{ t('terms.serviceContent') }}</p>

							<h3>{{ t('terms.riskTitle') }}</h3>
							<p>{{ t('terms.riskContent') }}</p>
						</div>
					</van-collapse-item>
				</van-collapse>

				<van-cell>
					<van-checkbox v-model="form.termsAgreed" shape="square">{{
						t('signature.agreeTerms')
					}}</van-checkbox>
				</van-cell>
			</van-cell-group>
		</div>

		<!-- 签名区域 -->
		<div class="section">
			<div class="section-header">
				<van-icon name="edit" size="20" />
				<h2>{{ t('review.confirmSignature') }}</h2>
			</div>
			<van-cell-group>
				<van-cell :title="t('review.confirmSignature')">
					<template #value>
						<div class="signature-field">
							<div
								v-if="
									orderStore.service.customer_sign ||
									form.customerSignature
								"
								class="signature-preview"
							>
								<img
									:src="
										orderStore.service.customer_sign ||
										form.customerSignature
									"
									:alt="t('signature.customerSign')"
								/>
							</div>
							<van-button
								v-else
								size="small"
								type="primary"
								plain
								@click="showSignature('customer')"
								>{{ t('review.clickSign') }}</van-button
							>
						</div>
					</template>
				</van-cell>
				<!-- <van-field
					v-model="form.customerSignatureDate"
					label="日期"
					placeholder="选择日期"
					readonly
					@click="showDatePicker('customer')"
				>
					<template #right-icon>
						<van-icon
							name="calendar"
							@click="showDatePicker('customer')"
						/>
					</template>
				</van-field> -->
			</van-cell-group>
		</div>

		<!-- 提交按钮 -->
		<div v-if="!orderStore.service.customer_sign" class="submit-button">
			<van-button
				round
				block
				type="primary"
				size="large"
				@click="submitForm"
				>{{ t('common.confirm') }}</van-button
			>
		</div>

		<!-- 签名弹窗 -->
		<van-popup v-model:show="showSign" position="bottom" round>
			<div class="signature-popup">
				<div class="signature-header">
					<h3>
						{{
							currentSignatureType === 'customer'
								? t('signature.customerSign')
								: t('signature.electricianSign')
						}}
					</h3>
					<van-button
						plain
						type="primary"
						size="small"
						@click="showSign = false"
						>{{ t('common.cancel') }}</van-button
					>
				</div>

				<!-- Vant 签名组件 -->
				<van-signature
					ref="signatureRef"
					:pen-color="'#000'"
					:line-width="3"
					background-color="#f7f8fa"
					@submit="saveSignature"
					@clear="onClear"
					:clear-button-text="t('signature.clear')"
					:confirm-button-text="t('signature.confirm')"
					style="height: 300px"
				/>
			</div>
		</van-popup>

		<!-- 日期选择器 -->
		<van-popup v-model:show="showDatePickerPopup" position="bottom">
			<van-date-picker
				v-model="currentDate"
				@confirm="onDateConfirm"
				@cancel="showDatePickerPopup = false"
			/>
		</van-popup>
	</div>
</template>

<script setup>
import { ref, reactive, watch, computed } from 'vue'
import { showToast, showImagePreview } from 'vant'
import { useOrderStore } from '@/stores/order'
import { useRoute, useRouter } from 'vue-router'
import { getOrderDetailApi } from '@/api/user'
import { useI18n } from 'vue-i18n'
const { t } = useI18n()
const route = useRoute()
const router = useRouter()
const orderStore = useOrderStore()

// 获取今天日期字符串
function getTodayStr() {
	const d = new Date()
	const y = d.getFullYear()
	const m = (d.getMonth() + 1).toString().padStart(2, '0')
	const day = d.getDate().toString().padStart(2, '0')
	return `${y}-${m}-${day}`
}

// 表单数据
const form = reactive({
	termsAgreed: orderStore.service.customer_sign,
	customerSignature: '',
})

// 监听路由变化
watch(
	() => route.query,
	(query) => {
		console.log('signature路由变化:', query)
		if (query.order_no) {
			getDetail(query.order_no)
		}
	},
	{ immediate: true }
)

async function getDetail(newOrderNo) {
	console.log('signature订单号:', newOrderNo)

	if (newOrderNo) {
		const res = await getOrderDetailApi(newOrderNo)
		if (res.data) {
			orderStore.fillFromOrderDetail(res.data)
			form.termsAgreed = orderStore.service.customer_sign
			console.log('用户信息', orderStore.customer.mobile)
		}
	}
}
// 签名相关状态
const showSign = ref(false)
const signatureRef = ref(null)
const currentSignatureType = ref('customer') // 'customer' 或 'electrician'

// 日期选择器相关
const showDatePickerPopup = ref(false)
const currentDateType = ref('')
const currentDate = ref([
	new Date().getFullYear(),
	new Date().getMonth() + 1,
	new Date().getDate(),
])

// 折叠面板控制
const activeCollapse = ref([])

// 打开视频链接
const openVideo = () => {
	showToast(t('signature.openVideo'))
	// 实际项目中替换为真实链接
	// window.open('https://ecoflow.com/installation-video', '_blank');
}

// 打开检查清单
const openChecklist = () => {
	showToast(t('signature.openChecklist'))
	// 实际项目中替换为真实链接
	// window.open('https://ecoflow.com/checklist', '_blank');
}

// 显示签名面板
const showSignature = (type) => {
	currentSignatureType.value = type
	showSign.value = true
}

// 保存签名
const saveSignature = (data) => {
	console.log(data)
	// if (currentSignatureType.value === 'customer') {
	form.customerSignature = data.image
	// } else {
	// 	form.electricianSignature = data.image
	// }
	showSign.value = false
}

// 清除签名
const onClear = () => {
	signatureRef.value?.clear()
}

// 显示日期选择器
const showDatePicker = (type) => {
	currentDateType.value = type
	showDatePickerPopup.value = true
}

// 日期选择确认
const onDateConfirm = ({ selectedValues }) => {
	const [year, month, day] = selectedValues
	const formattedDate = `${year}-${month.toString().padStart(2, '0')}-${day
		.toString()
		.padStart(2, '0')}`

	if (currentDateType.value === 'customer') {
		// form.customerSignatureDate = formattedDate
	} else {
		// form.electricianSignatureDate = formattedDate
	}

	showDatePickerPopup.value = false
}

// 提交表单
const submitForm = () => {
	if (!form.customerSignature) {
		showToast(t('signature.pleaseSign'))
		return
	}
	if (route.query.from === 'review') {
		router.replace({
			path: '/customer-review',
			query: { sign: form.customerSignature },
		})
		return
	}
	if (!form.termsAgreed) {
		showToast(t('signature.pleaseAgreeTerms'))
		return
	}
	showToast(t('signature.submitSuccess'))
}

const serviceTimeDisplay = computed(() => {
	const time = orderStore.service.service_time
	if (!time) return ''
	// 只保留第一个和最后一个时间段
	const arr = time.split(',')
	if (arr.length === 1) return arr[0]
	return `${arr[0]}-${arr[arr.length - 1]}`
})

function toImageArray(val) {
	if (!val) return []
	if (Array.isArray(val)) return val
	if (typeof val === 'string') {
		return val
			.split(',')
			.map((s) => s.trim())
			.filter(Boolean)
	}
	return []
}

// 适配图片字段并拼接为一个数组
const allImages = computed(() => {
	return [
		...toImageArray(orderStore.service.product_image),
		...toImageArray(orderStore.service.product_sn_image),
		...toImageArray(orderStore.service.scene_image),
	]
})

// 修改图片展示
const previewImage = (idx) => {
	console.log(allImages.value)
	showImagePreview({
		images: allImages.value,
		startPosition: idx,
	})
}
</script>

<style scoped>
.ecoflow-form {
	padding: 16px;
	padding-bottom: 80px;
	background-color: #f8f9fa;
	max-width: 800px;
	margin: 0 auto;
}

.section {
	background-color: white;
	border-radius: 12px;
	padding: 16px;
	margin-bottom: 20px;
	box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
}

.section-header {
	display: flex;
	align-items: center;
	gap: 10px;
	margin-bottom: 16px;
	padding-bottom: 12px;
	border-bottom: 1px solid #f0f0f0;
}

.section-header h2 {
	margin: 0;
	font-size: 18px;
	font-weight: bold;
	color: #1989fa;
}

.terms-content {
	padding: 10px;
	font-size: 14px;
	line-height: 1.6;
	color: #666;
}

.terms-content h3 {
	color: #1989fa;
	font-size: 16px;
	margin-top: 10px;
	margin-bottom: 8px;
}

.signature-field {
	display: flex;
	align-items: center;
	min-height: 40px;
}

.signature-preview {
	width: 120px;
	height: 60px;
	border: 1px dashed #ccc;
	border-radius: 4px;
	overflow: hidden;
}

.signature-preview img {
	width: 100%;
	height: 100%;
	object-fit: contain;
}

.signature-popup {
	padding: 16px;
	background-color: #fff;
}

.signature-header {
	display: flex;
	justify-content: space-between;
	align-items: center;
	margin-bottom: 15px;
}

.signature-header h3 {
	margin: 0;
	font-size: 16px;
}

.submit-button {
	position: fixed;
	bottom: 20px;
	left: 16px;
	right: 16px;
	z-index: 100;
}

/* 自定义表格样式 */
.van-cell {
	align-items: center;
}

.van-field__label {
	flex: 0 0 120px;
}

.image-scroll-list {
	display: flex;
	flex-direction: row;
	overflow-x: auto;
	gap: 12px;
	padding-bottom: 8px;
}

.image-item {
	flex: 0 0 auto;
	width: 100px;
	height: 100px;
	display: flex;
	align-items: center;
	justify-content: center;
}
</style>
